var express = require("express");
var router = express.Router();

const { generateOrderNumber } = require("../utils/util");
const fileService = require("../service/fileService");

const { BASE_URL } = require("../utils/constant");

router.get("/", async function (req, res, next) {
    const { current, pageSize } = req.query;
    const searchParams = {};

    const data = await fileService.findAll(
        parseInt(current || 1),
        parseInt(pageSize || 10),
        searchParams
    );

    data.rows = data.rows.map((item) => {
        return {
            ...item.dataValues,
            forwardUrl: BASE_URL + "detail?id=" + item.id,
        };
    });
    // console.log("data",data);
    res.send(data);
});
router.get("/getById", async function (req, res, next) {
    let id = req.query.id;
    let data = await fileService.findById(id);
    res.send(data);
});
router.post("/", async function (req, res, next) {
    // let id = generateOrderNumber();
    let id = req.body.id;
    let type = req.body.type;
    let data = await fileService.findById(id);
    if (data) {
        res.send({ status: 0, message: "文件已存在" });
    } else {
        let file = {
            id,
            title: id + "." + req.body.type,
            type,
            createTime: new Date().format("yyyy-MM-dd hh:mm:ss"),
        };
        await fileService.create(file);
        file.forwardUrl = BASE_URL + "detail?id=" + id;
        res.send({status: 1, data: file});
    }
});

router.put("/updateUrl/:id", async function (req, res, next) {
    let id = req.params.id;
    let url = req.body.url;
    await fileService.updateUrl(id, url);
    res.send({ status: 1 });
});

router.put("/updateWriteName/:id", async function (req, res, next) {
    let id = req.params.id;
    let writeName = req.body.writeName;
    await fileService.updateWriteName(id, writeName);
    res.send({ status: 1 });
});

router.delete("/:id", async function (req, res, next) {
    let id = req.params.id;

    await fileService.delete(id);
    res.send({ status: 1 });
});

module.exports = router;
